import SwiftUI
import Foundation

struct SecuritySettingsView: View {
    @EnvironmentObject var dataManager: DataManager
    @State private var showingAlert = false
    @State private var alertMessage = ""
    @State private var isLoading = false
    @State private var biometricToggleState = false
    
    var body: some View {
        NavigationView {
            ZStack {
                // 三色渐变背景
                LinearGradient(
                    gradient: Gradient(colors: [
                        Color(red: 0.15, green: 0.15, blue: 0.15),
                        Color(red: 0.1, green: 0.1, blue: 0.1),
                        Color(red: 0.05, green: 0.05, blue: 0.05)
                    ]),
                    startPoint: .topLeading,
                    endPoint: .bottomTrailing
                )
                .ignoresSafeArea()
                
                ScrollView {
                    VStack(spacing: 24) {
                        headerView
                        biometricSection
                    }
                    .padding()
                }
            }
            .navigationTitle("Security Settings")
            .navigationBarTitleDisplayMode(.large)
        }

        .alert("Alert", isPresented: $showingAlert) {
            Button("OK") { }
        } message: {
            Text(alertMessage)
        }
        .onReceive(dataManager.$currentUser) { user in
            if let user = user {
                biometricToggleState = user.biometricLoginEnabled
            }
        }
    }
    
    private var headerView: some View {
        VStack(spacing: 16) {
            Text("Manage your account security")
                .font(.subheadline)
                .foregroundColor(.gray)
        }
    }
    

    
    private var biometricSection: some View {
        VStack(alignment: .leading, spacing: 12) {
            HStack {
                Image(systemName: "faceid")
                    .foregroundColor(.orange)
                Text("Biometric Login")
                    .font(.headline)
                    .foregroundColor(.white)
                Spacer()
            }
            
            if let user = dataManager.currentUser {
                HStack {
                     Toggle("Enable Biometric Login", isOn: $biometricToggleState)
                         .foregroundColor(.white)
                         .disabled(isLoading)
                         .onChange(of: biometricToggleState) { newValue in
                             if newValue != user.biometricLoginEnabled {
                                 if newValue {
                                     enableBiometricLogin()
                                 } else {
                                     disableBiometricLogin()
                                 }
                             }
                         }
                         .onAppear {
                             biometricToggleState = user.biometricLoginEnabled
                         }
                     
                     if isLoading {
                         Spacer()
                         ProgressView()
                             .scaleEffect(0.8)
                             .progressViewStyle(CircularProgressViewStyle(tint: .orange))
                     }
                 }
            }
        }
        .padding()
        .background(
            RoundedRectangle(cornerRadius: 16)
                .fill(Color.white.opacity(0.08))
                .overlay(
                    RoundedRectangle(cornerRadius: 16)
                        .stroke(Color.white.opacity(0.2), lineWidth: 1)
                )
        )
        .shadow(color: Color.black.opacity(0.3), radius: 8, x: 0, y: 4)
        .shadow(color: Color.white.opacity(0.1), radius: 2, x: 0, y: -1)
    }
    
    private func formatDate(_ date: Date) -> String {
        let formatter = DateFormatter()
        formatter.dateStyle = .medium
        return formatter.string(from: date)
    }
    
    private func enableBiometricLogin() {
        // 首先检查生物识别是否可用
        guard dataManager.isBiometricAvailable() else {
            alertMessage = dataManager.currentLanguage == "zh" ? "生物识别功能不可用" : "Biometric authentication not available"
            showingAlert = true
            // 恢复Toggle状态
            biometricToggleState = false
            return
        }
        
        isLoading = true
        
        // 触发生物识别验证
        dataManager.authenticateWithBiometrics { success, error in
            DispatchQueue.main.async {
                isLoading = false
                
                if success {
                    // 验证成功后启用生物识别
                    dataManager.enableBiometricLogin()
                    // 确保Toggle状态与实际状态同步
                    biometricToggleState = true
                    
                    if AppConfig.enableDebugLogging {
                        print("[DEBUG] SecuritySettingsView: 生物识别登录已启用")
                    }
                } else {
                    // 验证失败，恢复Toggle状态并显示错误信息
                    biometricToggleState = false
                    let errorMsg = error ?? (dataManager.currentLanguage == "zh" ? "生物识别验证失败" : "Biometric authentication failed")
                    alertMessage = errorMsg
                    showingAlert = true
                    
                    if AppConfig.enableDebugLogging {
                        print("[DEBUG] SecuritySettingsView: 生物识别验证失败 - \(errorMsg)")
                    }
                }
            }
        }
    }
    
    private func disableBiometricLogin() {
        // 禁用生物识别时也需要验证身份
        guard dataManager.isBiometricAvailable() else {
            // 如果生物识别不可用，直接禁用
            dataManager.disableBiometricLogin()
            biometricToggleState = false
            return
        }
        
        isLoading = true
        
        // 触发生物识别验证以确认身份
        dataManager.authenticateWithBiometrics { success, error in
            DispatchQueue.main.async {
                isLoading = false
                
                if success {
                    // 验证成功后禁用生物识别
                    dataManager.disableBiometricLogin()
                    // 确保Toggle状态与实际状态同步
                    biometricToggleState = false
                    
                    if AppConfig.enableDebugLogging {
                        print("[DEBUG] SecuritySettingsView: 生物识别登录已禁用")
                    }
                } else {
                    // 验证失败，恢复Toggle状态并显示错误信息
                    biometricToggleState = true
                    let errorMsg = error ?? (dataManager.currentLanguage == "zh" ? "需要验证身份才能禁用生物识别" : "Authentication required to disable biometric login")
                    alertMessage = errorMsg
                    showingAlert = true
                    
                    if AppConfig.enableDebugLogging {
                        print("[DEBUG] SecuritySettingsView: 禁用生物识别验证失败 - \(errorMsg)")
                    }
                }
            }
        }
    }
}

#Preview {
    SecuritySettingsView()
        .environmentObject(DataManager.shared)
}